package com.dding.cms.base.dao.impl;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.dding.core.log.ILogger;
import org.dding.core.log.LoggerFactory;
import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;

import com.dding.cms.base.dao.ChannelDao;
import com.dding.cms.base.entity.Channel;
import com.dding.cms.base.web.util.TreeNode;

public class ChannelDaoImpl implements ChannelDao {

	private ILogger logger = LoggerFactory.getLogger(getClass());
	public static final TreeNode root = new TreeNode();

	static {
		root.setId("");
		root.setName("根目录");
		root.setOpen(true);
		root.setIsParent("true");
	}

	@SuppressWarnings("unchecked")
	@Override
	public String getChannelTree() throws Throwable {
		LazyList<Model> list = Channel.find("parent_id is null");
		buildJsonData(list, root);
		ObjectMapper mapper = new ObjectMapper();
		StringWriter sw = new StringWriter();
		mapper.writeValue(sw, root);
		return sw.toString();
	}

	private void buildJsonData(LazyList<? extends Model> list, TreeNode parent) {
		List<TreeNode> children = new ArrayList<TreeNode>();
		for (Model model : list) {

			// Object object = model.get("is_display");
			// if (object != null) {
			// if (!(Boolean) object) {
			// continue;
			// }
			// }

			TreeNode channel = new TreeNode();
			Integer channelId = (Integer) model.get("channel_id");
			channel.setId(channelId.toString());
			String channelName = (String) model.get("channel_name");
			channel.setName(channelName);
			channel.setOpen(false);
			channel.setUserdata("&model_id=" + model.get("model_id")
					+ "&site_id=" + model.get("site_id"));
			if (!addChildToList(model, channel)) {
				channel.setIsParent("false");
			} else {
				channel.setIsParent("true");
			}
			children.add(channel);
		}
		Collections.sort(children, new Comparator<TreeNode>() {

			@Override
			public int compare(TreeNode o1, TreeNode o2) {
				if ("true".equalsIgnoreCase(o1.getIsParent())
						&& "false".equalsIgnoreCase(o2.getIsParent()))
					return -1;
				if ("false".equalsIgnoreCase(o1.getIsParent())
						&& "true".equalsIgnoreCase(o2.getIsParent()))
					return 1;
				return 0;
			}
		});
		parent.setChildren(children);
	}

	private boolean addChildToList(Model m, TreeNode parent) {

		LazyList<Channel> children = m.getAll(Channel.class);
		if (children == null || children.size() == 0)
			return false;

		buildJsonData(children, parent);
		return true;
	}
}
